import { Leafer, Pen, DragEvent, App, Rect, Ellipse, Polygon } from "leafer-ui";
import { ITool, IToolConfig } from "../types";
export const ShapeTool: ITool = ({app, config,historyUtil,box})  => {
  let shape: Rect | Ellipse | Polygon | null = null;
  let isDrawing = false;
  let startPoint = { x: 0, y: 0 };
  const startDrawing = (e: DragEvent) => {
    if (e?.multiTouch) return (isDrawing = false);
    if (app.editor.editing) return;
    isDrawing = true;
    const point = e.getPagePoint();
    startPoint = { x: point.x, y: point.y };
    const attrs = {
      width: 0,
      height: 0,
      fill: "transparent",
      x: point.x,
      y: point.y,
      stroke: config.shape.stroke,
      strokeWidth: config.shape.strokeWidth/(app.data?.fitScale??1),
      editable: true,
    };
    if (config.shape.type === "rect") {
      shape = new Rect(attrs);
    } else if (config.shape.type === "circle") {
      shape = new Ellipse(attrs);
    } else {
      shape = new Polygon({
        ...attrs,
        sides:3,
      });
    }
    box.add(shape);
  };
  const continueDrawing = (e: DragEvent) => {
    if (e?.multiTouch) return (isDrawing = false);
    if (!isDrawing || !shape) return;
    const point = e.getPagePoint();
    // 根据拖拽距离计算宽度和高度
    const width = Math.abs(point.x - startPoint.x);
    const height = Math.abs(point.y - startPoint.y);

    // 更新矩形尺寸
    shape.width = width;
    shape.height = height;

    // 如果从右下向左上拖拽，更新位置
    shape.x = Math.min(startPoint.x, point.x);
    shape.y = Math.min(startPoint.y, point.y);
  };
  const stopDrawing = () => {
    isDrawing = false;
    shape = null; // 重置形状引用，准备下一次绘制
    historyUtil.commit(box.toJSON());
  };
  const eventsMap = {
    [DragEvent.START]: startDrawing,
    [DragEvent.DRAG]: continueDrawing,
    [DragEvent.END]: stopDrawing,
  };
  return {
    eventsMap,
    active: () => {},
    deactive: () => {
      
    },
  };
};
